import React, { useState, useEffect, useRef } from 'react';
import './CustomSelect.css';

/**
 * 自定义下拉选择组件
 * @param {Array} options - 选项数组，格式：[{ value: any, label: string }, ...]
 * @param {any} value - 当前选中的值（如果不需要记录选中状态，可传入 null）
 * @param {Function} onChange - 选择变化回调函数 (value) => void
 * @param {string} placeholder - 占位符文本
 * @param {boolean} showSelected - 是否显示选中状态（默认 true）
 * @param {string} className - 额外的 CSS 类名
 */
const CustomSelect = ({ 
  options = [], 
  value = null, 
  onChange = () => {}, 
  placeholder = '请选择',
  showSelected = true,
  className = ''
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const selectRef = useRef(null);

  // 查找当前选中项（如果允许显示选中状态）
  // 处理 value 为 null、undefined 或空字符串的情况
  const normalizedValue = value === null || value === undefined ? null : value;
  const selectedOption = showSelected ? options.find(opt => {
    // 精确匹配值
    return opt.value === normalizedValue;
  }) : null;
  // 如果选中的是占位选项（空值）或未选中，显示 placeholder
  const displayText = selectedOption && selectedOption.value !== '' && selectedOption.value !== null 
    ? selectedOption.label 
    : placeholder;

  // 点击外部关闭下拉
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (selectRef.current && !selectRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  // 处理选项点击
  const handleOptionClick = (optionValue) => {
    onChange(optionValue);
    setIsOpen(false);
  };

  // 切换下拉状态
  const toggleDropdown = () => {
    setIsOpen(!isOpen);
  };

  return (
    <div 
      ref={selectRef}
      className={`custom-select ${isOpen ? 'custom-select--open' : ''} ${className}`}
    >
      <div 
        className="custom-select__trigger"
        onClick={toggleDropdown}
      >
        <span className={`custom-select__value ${!selectedOption ? 'custom-select__value--placeholder' : ''}`}>
          {displayText}
        </span>
        <span className={`custom-select__arrow ${isOpen ? 'custom-select__arrow--open' : ''}`}>
          ▼
        </span>
      </div>
      
      {isOpen && (
        <div className="custom-select__dropdown">
          <div className="custom-select__options">
            {options.map((option, index) => {
              // 判断是否为选中项（排除占位选项）
              const isSelected = showSelected && option.value === normalizedValue && option.value !== '' && option.value !== null;
              return (
                <div
                  key={index}
                  className={`custom-select__option ${isSelected ? 'custom-select__option--selected' : ''}`}
                  onClick={() => handleOptionClick(option.value)}
                >
                  {option.label}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
};

export default CustomSelect;

